package com.dylon.imgOperate;

import com.dylon.utils.ChineseToUnicode;
import com.madgag.gif.fmsware.AnimatedGifEncoder;
import com.madgag.gif.fmsware.GifDecoder;
import sun.awt.SunHints;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ImageWaterMarkTest {
	
	/** 给图片添加水印 */
	public static void addWaterMark() {
        
		//"Dialog","DialogInput","Lucida Bright","Lucida Sans","Lucida Sans Typewriter","Monospaced","SansSerif","Serif"
		Font font = new Font("SansSerif", Font.BOLD, 30); //水印字体
//		String waterMarkContent = "测试牛逼的水印技术";
		String waterMarkContent= gbEncoding( "测试牛逼的水印技术" ).replaceAll("\\\\u", "\\u"); //水印内容 
//		String waterMarkContent="\u6d4b\u8bd5\u725b\u903c\u7684\u6c34\u5370\u6280\u672f"; //水印内容
		try {
			String imageURL = "https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=3101694723,748884042&os=1763536506,877714758&simid=3371250864,260556217&pn=7&rn=1&di=22110&ln=1698&fr=&fmq=1625542653765_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fcdn.duitang.com%252Fuploads%252Fblog%252F201306%252F25%252F20130625150506_fiJ2r.jpeg%26refer%3Dhttp%253A%252F%252Fcdn.duitang.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1628134654%26t%3D415d15ba446166f15299f9e729380707&rpstart=0&rpnum=0&adpicid=0&nojc=undefined";
			BufferedImage buImage = BufferedImageTest.getRemoteBufferedImage(imageURL);
			int width = buImage.getWidth(); //图片宽
			int height = buImage.getHeight(); //图片高

			//添加水印
			BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(buImage, 0, 0, width, height, null);
			g.setColor(Color.RED); //水印颜色
			g.setFont(font); //水印字体
			//int x = width -2*getWatermarkLength(waterMarkContent, g); //这是一个计算水印位置的函数，可以根据需求添加
			//int y = height - 1*getWatermarkLength(waterMarkContent, g);
			g.drawString(waterMarkContent, 10,  height-30); //水印位置
			g.dispose(); //释放资源

			FileOutputStream outImgStream = new FileOutputStream("C:\\Users\\mlht\\Pictures\\addWaterMark.jpg");
			ImageIO.write(bufferedImage, "jpg", outImgStream);
			System.out.println("添加水印完成");
			outImgStream.flush();
			outImgStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void getGifSticker(String markContent ) throws FontFormatException, IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			GifDecoder decoder = new GifDecoder();
			URL urli = new URL("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%8A%A8%E5%9B%BE&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=2962820158,235896407&os=1104491171,2658951222&simid=0,0&pn=1&rn=1&di=111980&ln=1671&fr=&fmq=1625543345377_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252F5b0988e595225.cdn.sohucs.com%252Fimages%252F20180103%252F87c6ca450dfb4f1bb13ed453846baea4.gif%26refer%3Dhttp%253A%252F%252F5b0988e595225.cdn.sohucs.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1628135345%26t%3D5517901b824dc545a674ed4028616b65&rpstart=0&rpnum=0&adpicid=0&nojc=undefined");
			InputStream is = urli.openStream();
			//读入gif数据流
			decoder.read(is);
			//获取GIF的宽高
			Dimension dimension = decoder.getFrameSize();
			int height = (int)dimension.getHeight();
			
			//读取帧数
			int frameCount = decoder.getFrameCount();
			AnimatedGifEncoder encoder = new AnimatedGifEncoder();
			String url = "C:\\Users\\gefan\\Desktop\\worknote\\新建文件夹\\"+ System.currentTimeMillis()+".gif";
			encoder.start(url);
			encoder.setRepeat(0);
			Graphics2D g = null;
			Font font = new Font("微软雅黑", Font.BOLD, 30); //水印字体
			/**
			 * 对GIF进行拆分
			 * 每一帧进行文字处理
			 * 组装
			 */
			for (int i = 0; i < frameCount; i++) {
				//初始化图像
				g =  (Graphics2D) decoder.getFrame(i).getGraphics();
				/**
				 * RenderingHint是对图片像素，锯齿等等做的优化，可保证生成的图片放大锯齿点阵也不会很明显
				 */
				g.setRenderingHint(SunHints.KEY_ANTIALIASING, SunHints.VALUE_ANTIALIAS_ON);
			    g.setRenderingHint(SunHints.KEY_TEXT_ANTIALIASING, SunHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
				g.setColor(Color.YELLOW); 
				g.setFont(font);
                //设置打印文字和坐标
				g.drawString(markContent, 12, height-25);
				g.dispose();
				//组装每一帧
				encoder.addFrame(decoder.getFrame(i));
				//设置每帧的切换时间
				if (i != frameCount - 1) {
					encoder.setDelay(decoder.getDelay(i));
				}
			}
			encoder.finish();
			byte b[] = outputStream.toByteArray();
		}finally {
			try {
				if (null != outputStream)
					outputStream.close();
			} catch (IOException e) {
				
			}
		}
		System.out.println("处理完成");
	}
	
	public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
		return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
	}

	public static String gbEncoding(final String gbString) {         
    	char[] utfBytes = gbString.toCharArray();               
        String unicodeBytes = "";                
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {  
            String hexB = Integer.toHexString(utfBytes[byteIndex]);                       
            if (hexB.length() <= 2) {                           
                hexB = "00" + hexB;                     
            }                       
            unicodeBytes = unicodeBytes + "\\\\u" + hexB;                   
        }                 
        return unicodeBytes;            
    }    
	
	public static void main(String[] args) {
//		 addWaterMark();
		
		 String waterMarkContent= gbEncoding( "测试牛逼的水印技术" );
		 System.out.println(waterMarkContent.replaceAll("\\\\u", "\\u"));
//		 System.out.println(ChineseToUnicode.decodeUnicode( waterMarkContent ));
		 System.out.println(ChineseToUnicode.decodeUnicode( waterMarkContent.replaceAll("\\\\u", "\\u") ));
//		try {
//			getGifSticker("水印技术");
//		} catch (FontFormatException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
//		
//		try {
//			URL urli = new URL("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=3101694723,748884042&os=1763536506,877714758&simid=3371250864,260556217&pn=7&rn=1&di=22110&ln=1698&fr=&fmq=1625542653765_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fcdn.duitang.com%252Fuploads%252Fblog%252F201306%252F25%252F20130625150506_fiJ2r.jpeg%26refer%3Dhttp%253A%252F%252Fcdn.duitang.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1628134654%26t%3D415d15ba446166f15299f9e729380707&rpstart=0&rpnum=0&adpicid=0&nojc=undefined");
//			InputStream is = urli.openStream();
//			BufferedInputStream buff = new BufferedInputStream(is);     
//			byte[] mapObj = new byte[is.available()];     
//		   	buff.read(mapObj, 0, is.available());
//			
//		   	String type = "";     
//		    ByteArrayInputStream bais = null;     
//		    MemoryCacheImageInputStream mcis = null;     
//		    try {     
//		       bais = new ByteArrayInputStream(mapObj);     
//		       mcis = new MemoryCacheImageInputStream(bais);     
//		       Iterator itr = ImageIO.getImageReaders(mcis);  
//		       while (itr.hasNext()) {   
//		    	   ImageReader reader = (ImageReader) itr.next();     
//		           if (reader instanceof GIFImageReader) {     
//		               type = "gif";     
//		           } else if (reader instanceof JPEGImageReader) {     
//		               type = "jpg";     
//		           } else if (reader instanceof PNGImageReader) {     
//		               type = "png";     
//		           } else if (reader instanceof BMPImageReader) {     
//		               type = "bmp";     
//		           }
//		       }     
//		    } finally {
//		       if (bais != null) {     
//		           try {     
//		               bais.close();     
//		           } catch (IOException ioe) {     
//		    
//		           }     
//		       }     
//		    
//		       if (mcis != null) {     
//		           try {     
//		               mcis.close();     
//		           } catch (IOException ioe) {     
//		    
//		           }     
//		       }     
//		   }
//		   System.out.println("图片类型："+ type);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}
}